package top.yqingyu.trans$client.api;


import java.util.concurrent.ConcurrentLinkedQueue;


public class ConnectionPool {

    private ConnectionConfig config;
    private boolean isInit = true;

    private final ConcurrentLinkedQueue<Connection> amp = new ConcurrentLinkedQueue<>();

    public ConnectionPool() {
    }

    public ConnectionPool(ConnectionConfig config) throws Exception {
        this.config = config;
        this.init();
    }

    public void init() throws Exception {
        isInit = false;
        short poolMin = config.pool_min;
        for (byte i = 0; i < poolMin; i++) {
            amp.add(Connection.getInstance(config));
        }
    }

    public Connection next() throws Exception {
        if (isInit) {
            throw new IllegalStateException("The init method has not been executed yet !!");
        }
        if (amp.size() < config.pool_max) {
            Connection instance = Connection.getInstance(config);
            amp.add(instance);
            return instance;
        } else {
            Connection poll;
            do {
                poll = amp.poll();
                if (poll == null || (poll.isClose && amp.size() < config.pool_max)) {
                    Connection instance = Connection.getInstance(config);
                    amp.add(instance);
                    return instance;
                }
                amp.add(poll);
            } while (poll.isClose);
            return poll;
        }
    }


}
